/**
 * Created by tongjunshui on 17/6/9.
 */
var express = require('express');
var router = express.Router();

var async = require('async');
var settings = require('../../settings');
var superagent = require('superagent');

var moment = require('moment');
var ObjValues = require ('object.values');
var dbDao = require('../../models/dbBase.js');

//添加订单
router.post('/', function (req,res){
    var orderItems = req.body.orderItems;
    var phone = req.body.phone;
    var gymId = req.body.gymId;
    var wxopenid = req.body.wxopenid;

    var orderData = {
        channel: "WECHATQCG",
        gymId: gymId,
        phone: phone,
        userId:wxopenid,
        desc: "小时预定",
        data: orderItems
    };
    console.log(orderData);
    //请求订单
    var url = settings.gymServiceBaseUrl +"/api/reserve/createOrderHours";
    superagent.post(url).send(orderData).end(function (err, body) {
        if(err){
            res.send({result: 'error', message:'创建失败'});
        }else{
            if (body.body.state === true) {
                res.send({result: 'success', data:{orderNo: body.body.orderId}});
            } else {
                res.send({result: 'error',message: body.body.message});
            }
        }
    })
})

router.post('/cancel/:id', function (req,res){
    var orderNo = req.params.id;
    if(!orderNo){
        res.send({result:'error',message:'无效的订单号'});
    }else{
        var sql = "update orders set orderStatus=? where id=?";
        var params = ['2', orderNo];
        dbDao.querys(sql, params, function (err, result) {
            if(err){

                res.send({result:'error',message:'取消订单失败'});
            }else{
                res.send({result:'success',data:{}});
            }
        });
    }
})
//我的订单
router.get('/my/:wxopenid', function (req,res){
    var wxopenId = req.params.wxopenid;

    /**
     * 资源分组算法,将资源按照场地分开
     * @param arr
     * @returns {{}}
     */
    function part(arr) {
        var newArr;
        if (arr.length <= 0) {
            return
        }
        var a = {};

        for (var i = 0; i < arr.length; i++) {
            if (a[arr[i].name]) {
                a[arr[i].name].push(arr[i]);

            } else {
                a[arr[i].name] = [];
                a[arr[i].name].push(arr[i]);
            }
        }
        return a;

    }

    /**
     * 组合算法,将每个场地的资源按照时间整合合并;
     * @param arr
     * @returns {Array}
     */
    function bijiao(x, y) {
        return x.beginTime - y.beginTime;
    }

    function group(arr) {
        arr.sort(bijiao);
        var newObj = [];
        var t = 0;
        newObj[t] = {beginTime: arr[0].beginTime, date: arr[0].date}
        for (var i = 0; i < arr.length - 1; i++) {
            if (arr[i + 1]) {
                if (arr[i].endTime == arr[i + 1].beginTime) {
                    newObj[t]['endTime'] = arr[i + 1].endTime;
                } else {
                    newObj[++t] = {beginTime: arr[i + 1].beginTime, date: arr[0].date}
                }
            }
        }
        newObj[t]["endTime"] = arr[arr.length - 1].endTime;
        return newObj;
    }

    function bigGroup(arr) {
        var bigarr = {};
        for (var i in arr) {
            bigarr[i] = group(arr[i]);
        }
        return bigarr;
    }

    var sql = "select * from orders where wxopenId=? and orderStatus=?";
    var sql2 = "select * from orders where wxopenId=?";
    var sql3 = "select * from OrderItem where orderId=?";
    var sql4 = "select * from GymResource where id=?";

    var params1 = [wxopenId, '0'];  //待支付
    var params2 = [wxopenId, '1'];  //已支付
    console.log(params2);

    var orderResult = [];
    var arrResult = [];
    var arrOrderResouce = [];
    dbDao.querys(sql2, [wxopenId], function (err, result3) {
        console.log("订单result3.length", result3.datas.length);

        orderResult = result3.datas;
        async.each(result3.datas, function (item, callback) {
            dbDao.querys( sql3, [item.id], function (err, result4) {

                item['clmItemId'] = result4.datas.map(function (ele, index) {
                    return ele.sourceId;
                });
                console.log(item['clmItemId']);
                arrResult.push(item);
                callback(null);

            });
        }, function (err) {
            console.log(arrResult);
            /**
             *  循环便利每一条订单;
             */
            async.each(arrResult, function (item, callback1) {
                /**
                 * 循环便利订单里每一条资源;
                 */
                item['clmresouce'] = []
                async.each(item.clmItemId, function (i, callback) {
                    console.log(i);
                    dbDao.querys( sql4, i, function (err, result) {
                        console.log(result);
                        item['clmresouce'].push(result.datas[0]);
                        callback();
                    })
                }, function (err) {
                    arrOrderResouce.push(item);
                    callback1()
                })
            }, function (err) {
                var arrOrderResouce2 = arrOrderResouce.map(function (ele, index) {
                    ele['part'] = part(ele.clmresouce);
                    return ele;
                });
                var arrOrderResouce3 = arrOrderResouce2.map(function (ele, index) {
                    ele['group'] = bigGroup(ele.part);
                    return ele;
                });
                arrOrderResouce3 = arrOrderResouce3.map(function (ele, index) {
                    ele['changDi'] = Object.keys(ele.group);
                    ele['shijian'] = ObjValues(ele.group)[0][0].date;
                    var t = ObjValues(ele.group).map(function (ele) {
                        return ele[0].beginTime;
                    }).sort()[0];
                    ele['startshijian'] = moment(t, "YYYYMMDDHHmmsss").format("MM/DD HH:mm");
                    return ele;
                })
                var data1 = arrOrderResouce3.filter(function (ele, index) {
                    return ele.orderStatus == "0";
                });
                var data2 = arrOrderResouce3.filter(function (ele, index) {
                    return ele.orderStatus == "1";
                });
                //res.json(arrOrderResouce3);
                res.send( {result:'success',
                    data: {
                        payingOrder: data1,
                        paiedOrder: data2,
                        allOrder: arrOrderResouce3
                    }
                })
            })
        })
    })
});

router.get('/detail/:orderNo', function (req,res){
    var orderNo = req.params.orderNo;
    function part(arr) {
        var newArr;
        if (arr.length <= 0) {
            return
        }
        var a = {};

        for (var i = 0; i < arr.length; i++) {
            if (a[arr[i].name]) {
                a[arr[i].name].push(arr[i]);

            } else {
                a[arr[i].name] = [];
                a[arr[i].name].push(arr[i]);
            }
        }
        return a;

    }

    /**
     * 组合算法,将每个场地的资源按照时间整合合并;
     * @param arr
     * @returns {Array}
     */
    function bijiao(x, y) {
        return x.beginTime - y.beginTime;
    }

    function group(arr) {
        arr.sort(bijiao);
        var newObj = [];
        var t = 0;
        newObj[t] = {beginTime: arr[0].beginTime, date: arr[0].date, price: arr[0].price}
        for (var i = 0; i < arr.length - 1; i++) {
            if (arr[i + 1]) {
                if (arr[i].endTime == arr[i + 1].beginTime) {
                    newObj[t]['endTime'] = arr[i + 1].endTime;
                } else {
                    newObj[++t] = {beginTime: arr[i + 1].beginTime, date: arr[0].date, price: arr[0].price}
                }
            }
        }
        newObj[t]["endTime"] = arr[arr.length - 1].endTime;
        return newObj;
    }

    function bigGroup(arr) {
        var bigarr = {};
        for (var i in arr) {
            bigarr[i] = group(arr[i]);
        }
        return bigarr;
    }

    /**
     * 拼接对象
     * @param arr
     * @returns {Array}
     */
    function pinjie(obj) {
        var arr = [];
        var t = -1
        for (i in obj) {
            for (var j = 0; j < obj[i].length; j++) {
                arr[++t] = {};
                arr[t]["name"] = i;
                Object.assign(arr[t], obj[i][j]);
            }

        }
        arr.sort(function (x, y) {
            return parseInt(x.name) - parseInt(y.name);
        });
        var newArr = arr.map(function (ele, index) {
            ele["zongjia"] = (ele.endTime - ele.beginTime) / 10000 * ele.price;
            ele["jiange"] = moment(ele.beginTime, "YYYYMMDDHHmmsss").format("HH:mm") + "-" + moment(ele.endTime, "YYYYMMDDHHmmsss").format("HH:mm");
            return ele;
        })
        return newArr;
    }

    if(!orderNo){
        res.send(
            {result:'error',data: {
            }
            });
    }else{
        //查询OrderItem
        var sql1 = "select * from OrderItem where orderId=?";
        //查询资源
        var sql2 = "select * from GymResource where id=?";
        //查询场馆具体名称
        var sql3 = "select * from GymFields where id=?";
        var arrResult;
        var arrResult1 = [];
        var ziyuan = [];
        dbDao.findById( ["orders", "id", orderNo], function (err, result) {
            dbDao.querys(sql1, [result.id], function (err, result1) {
                //res.json(result1.datas);
                if(err){
                    res.send({result:'error',message:'查询订单失败'});
                }
                arrResult = result1;
                async.each(arrResult.datas, function (item, callback1) {

                    dbDao.querys( sql2, [item.sourceId], function (err, result1) {
                        console.log(result1.datas);
                        ziyuan.push(result1.datas[0]);
                        callback1();
                    })

                }, function (err) {

                    dbDao.querys( sql3, [ziyuan[0].gymFieldId], function (err, result2) {
                        if(err){

                            res.send({result:'error',message:'查询订单失败'});
                        }else{
                            var t = part(ziyuan);
                            console.log('---t:',t);
                            var s = bigGroup(t);
                            console.log('---',s);
                            var FiledName = result2.datas[0].name;
                            var starttime = ObjValues(s)[0][0].date;
                            var starttime2 = moment(starttime, "YYYYMMDD").format("YYYY-MM-DD");
                            var obj = {
                                FiledName: FiledName,
                                starttime: starttime2,
                                details: pinjie(s)
                            }
                            Object.assign(obj, result);
                            res.send( {result:'success',
                                data: obj
                            });
                        }

                    });
                })
            })
        });
    }
})
module.exports = router;